<template>
  <div>
    <div class="container">
      <div class="nav1">询价清单以及要求</div>
      <div class="table1">
        <el-form label-width="120px" :disabled="true">
          <el-row :gutter="20">
            <!-- 询价信息 -->
            <el-col :span="12">
              <el-form-item label="询价日期：">
                <el-date-picker
                  v-model="form.inquiryDate"
                  type="date"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="货物种类：">
                <el-input
                  v-model="form.cargoType"
                  placeholder="请输入货物种类"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="运输方式：">
                <el-select v-model="form.shippingMethod" placeholder="请选择">
                  <el-option
                    v-for="item in shippingMethods"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="航线选择：">
                <el-select v-model="form.route" placeholder="请选择航线">
                  <!-- 此处可替换为图片选择组件 -->
                  <el-option
                    v-for="item in routes"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="起运港：">
                <el-input v-model="form.originPort" value="上海" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="目的地：">
                <el-input
                  v-model="form.destination"
                  placeholder="请输入目的地"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报价条款：">
                <el-select v-model="form.terms" placeholder="请选择">
                  <el-option
                    v-for="item in termsOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="货物描述：">
                <el-input
                  v-model="form.description"
                  placeholder="请输入货物描述"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="HS编码：">
                <el-input v-model="form.hsCode" value="84749000" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="柜型选择：">
                <el-select v-model="form.route" placeholder="请选择柜型">
                  <!-- 此处可替换为图片选择组件 -->
                  <el-option
                    v-for="item in containerTypes"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select> </el-form-item
            ></el-col>
          </el-row>
        </el-form>
      </div>
      <div class="nav2">产品信息</div>
      <div class="table2">
        <el-card class="product-table">
          <!-- 产品信息表格 -->
          <el-table :data="products" border style="width: 100%">
            <el-table-column
              prop="productNo"
              label="产品编号"
              width="120"
              align="center"
            />
            <el-table-column
              prop="productName"
              label="产品名称"
              width="120"
              align="center"
            />
            <el-table-column
              prop="totalPieces"
              label="总件数"
              width="120"
              align="center"
            />
            <el-table-column
              prop="totalWeight"
              label="总毛重 (kg)"
              width="120"
              align="center"
            />
            <el-table-column
              prop="totalVolume"
              label="总体积 (CBM)"
              width="120"
              align="center"
            />
            <el-table-column
              prop="totalPallets"
              label="总托数"
              width="120"
              align="center"
            />
          </el-table>

          <!-- 总计行 -->
          <div class="total-row">
            <span class="total-item">总件数: {{ totalPieces }}</span>
            <span class="total-item">总毛重: {{ totalWeight }} kg</span>
            <span class="total-item">总体积: {{ totalVolume }} CBM</span>
            <span class="total-item">总托数: {{ totalPallets }}</span>
          </div>
        </el-card>
      </div>
      <div class="nav3">报价</div>
      <div class="table3">
        <el-form
          :model="form1"
          label-width="110px"
          label-position="right"
          :disabled="isReadOnly"
        >
          <!-- 第一行 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报价条款">
                <el-select v-model="form1.quotationTerms" placeholder="请选择">
                  <el-option
                    v-for="item in termOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="RMB费用">
                <el-input v-model="form1.rmbCost" placeholder="单行输入" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 主要表单内容 -->
          <el-row :gutter="20">
            <!-- 左侧列 -->
            <el-col :span="12">
              <el-form-item label="海运费USD">
                <el-input
                  v-model="form1.seaTransportationCost"
                  placeholder="请输入"
                />
              </el-form-item>

              <el-form-item label="报价有效期">
                <el-date-picker
                  v-model="form1.validityPeriod"
                  type="date"
                  placeholder="请选择日期"
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item label="船公司">
                <el-input
                  v-model="form1.shippingCompany"
                  placeholder="单行输入"
                />
              </el-form-item>

              <el-form-item label="航次">
                <el-input v-model="form1.voyage" placeholder="单行输入" />
              </el-form-item>
            </el-col>

            <!-- 右侧列 -->
            <el-col :span="12">
              <el-form-item label="目的港费用合计">
                <el-input
                  v-model="form1.portOfDestinationCost"
                  placeholder="单行输入"
                />
              </el-form-item>

              <el-form-item label="海运费合计">
                <el-input
                  v-model="form1.seaTransportationTotalCost"
                  placeholder="请输入"
                />
              </el-form-item>

              <el-form-item label="报价有效期">
                <el-date-picker
                  v-model="form1.validityPeriod"
                  type="date"
                  placeholder="请选择日期"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="航程">
                <el-input
                  v-model="form1.voyageDistance"
                  placeholder="单行输入"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 文件上传 -->
          <el-form-item label="上传截图">
            <el-upload
              action="#"
              accept=".png,.jpg"
              :show-file-list="false"
              :before-upload="handleUpload"
            >
              <el-button type="primary">上传文件</el-button>
              <template #tip>
                <div class="upload-tip">支持扩展名：.png .jpg</div>
                <div v-if="fileList.length" class="uploaded-files">
                  <div
                    v-for="(file, index) in fileList"
                    :key="index"
                    class="file-item"
                  >
                    {{ file.name }} ({{ (file.size / 1024).toFixed(2) }}KB)
                    <el-button
                      type="danger"
                      size="small"
                      class="delete-btn"
                      @click.stop="removeFile(index)"
                    >
                      撤销
                    </el-button>
                  </div>
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <!-- 按钮 -->
      <div class="button-container">
        <el-button type="primary" :disabled="isReadOnly" @click="handleSave()"
          >保存</el-button
        >
        <el-button type="default" @click="handleCancel()">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { watch } from "vue";
import { ElMessage } from "element-plus";
import { onMounted } from "vue";
import {
  quoteSave,
  quoteUpdate,
  quoteQueryById,
  forwardInquiryUpdate
} from "@/api/forward/forward.js";

const route = useRoute();
const router = useRouter();
function handleSave() {
  // 保存逻辑
  if (route.query.source1 === "报价") {
    quoteBj();
  } else if (route.query.source1 === "修改报价") {
    quoteUpdate1();
  }
}
function handleCancel() {
  // 取消逻辑
  router.push("/forwardInquiry/list");
}
//设置报价表可用
const isReadOnly = ref(false);

const form = ref({
  inquiryDate: "",
  shippingMethod: "",
  originPort: "上海",
  terms: "",
  hsCode: "84749000",
  cargoType: "",
  route: "",
  destination: "",
  description: "",
  containerType: "20BP"
});

const shippingMethods = ["海运", "铁路", "公路", "空运", "多联式", "散货"];
const termsOptions = ["CFR", "CIF", "DDU", "DAP", "DDP", "其他"];
const containerTypes = ["拼箱", "20BP", "40GP", "20HQ", "40HQ", "20FR", "40FR"];
const routes = ["航线A", "航线B", "航线C"]; // 示例数据，需根据实际图片内容替换

// 产品信息
const products = ref([
  {
    productNo: 23,
    productName: "23",
    totalPieces: 23,
    totalWeight: 23,
    totalVolume: 23,
    totalPallets: 23
  },
  {
    productNo: 23,
    productName: "23",
    totalPieces: 23,
    totalWeight: 23,
    totalVolume: 23,
    totalPallets: 23
  },
  {
    productNo: 23,
    productName: "23",
    totalPieces: 23,
    totalWeight: 23,
    totalVolume: 23,
    totalPallets: 23
  }
]);

// 计算总合
const totalPieces = computed(() =>
  products.value.reduce((sum, item) => sum + item.totalPieces, 0)
);
const totalWeight = computed(() =>
  products.value.reduce((sum, item) => sum + item.totalWeight, 0)
);
const totalVolume = computed(() =>
  products.value.reduce((sum, item) => sum + item.totalVolume, 0)
);
const totalPallets = computed(() =>
  products.value.reduce((sum, item) => sum + item.totalPallets, 0)
);
//报价
// 表单数据
const form1 = ref({
  agentId: "",
  relationSn: "",
  sn: "",
  quotationTerms: "",
  rmbCost: "",
  seaTransportationCost: "",
  portOfDestinationCost: "",
  validityPeriod: "",
  seaTransportationTotalCost: "",
  shippingCompany: "",
  voyage: "",
  voyageDistance: "",
  screenshot: "",
  isDefault: "",
  createTime: "",
  status: "",
  type: "",
  reason: "",
  isConfirm: ""
});

// 报价条款选项
const termOptions = [
  { value: "CFR", label: "CFR" },
  { value: "CIF", label: "CIF" },
  { value: "DDU", label: "DDU" },
  { value: "DAP", label: "DAP" },
  { value: "DDP", label: "DDP" },
  { value: "other", label: "其他" }
];
// 上传文件
const fileList = ref([]);

// 修改上传处理函数
const handleUpload = file => {
  console.log("上传文件:", file);
  // 将文件添加到列表（实际项目需等上传成功后再添加）
  fileList.value.push({
    name: file.name,
    size: file.size,
    type: file.type
  });
  return false; // 阻止自动上传
};
const removeFile = index => {
  fileList.value.splice(index, 1);
};

//报价
async function quoteBj() {
  form1.value.relationSn = route.query.source2;
  let res = await quoteSave(form1.value);
  if (res.code == 200) {
    ElMessage.success("报价成功");

    router.push("/forwardInquiry/list");
  } else {
    ElMessage.error("报价失败");
  }
}
//查看报价
async function quoteById() {
  let res = await quoteQueryById({ id: route.query.source2 });
  if (res.code == 200) {
    form1.value = res.data;
    console.log(form1.value);
  }
}
// 修改报价
async function quoteUpdate1() {
  console.log(form1.value);
  let res = await quoteUpdate(form1.value);
  if (res.code == 200) {
    ElMessage.success("修改报价成功");
    router.push("/forwardInquiry/list");
  }
}

// 根据参数执行逻辑
const handleLogic = () => {
  if (route.query.source1 === "报价") {
    // 按钮A的逻辑
  } else if (route.query.source1 === "修改报价") {
    // 按钮B的逻辑
    onMounted(() => {
      quoteById();
    });
  } else if (route.query.source1 === "查看报价") {
    // 按钮C的逻辑
    onMounted(() => {
      quoteById();
      isReadOnly.value = true;
    });
  }
};

// 监听参数变化（应对浏览器前进/后退）
watch(
  () => route.query.source1,
  (newVal, oldVal) => {
    console.log("路由变化:", oldVal, "->", newVal);
    handleLogic();
  },
  { immediate: true }
);
</script>

<style scoped>
.container {
  max-width: 800px;
  padding: 20px;
  margin: 0 auto;
}

.el-radio-group {
  margin-top: 8px;
}

.el-select {
  width: 100%;
}

.table1 {
  padding-top: 15px;
  padding-right: 30px;
  background-color: #fff;
}

.nav1 {
  height: 40px;
  padding-left: 15px;
  line-height: 40px;
  background-color: #ddd;
}

.nav2 {
  height: 40px;
  padding-left: 15px;
  margin-top: 20px;
  line-height: 40px;
  background-color: #ddd;
}

.nav3 {
  height: 40px;
  padding-left: 15px;
  margin-top: 20px;
  line-height: 40px;
  background-color: #ddd;
}

.total-row {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  margin-top: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.total-item {
  margin: 0 15px;
  font-weight: 600;
  color: #606266;
}

.el-table {
  margin-top: 10px;
}

.table3 {
  padding-top: 15px;
  padding-right: 30px;
  background-color: #fff;
}

.el-form-item {
  margin-bottom: 18px;
}

.uploaded-files {
  margin-top: 10px;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 0;
}

.delete-btn {
  padding: 3px 6px;
  margin-left: 10px;
}
</style>
